package com.vueapi.controller.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Controller
public class ZipUploadController {

    @PostMapping("/upload-zip")
    public String uploadZipFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "Please select a ZIP file to upload.";
        }

        try {
            // 指定存储ZIP文件的本地路径
            String uploadDir = "D:\\uploadFile";
            String zipFilePath = uploadDir + file.getOriginalFilename();

            // 创建存储ZIP文件的目录（如果不存在）
            File uploadFolder = new File(uploadDir);
            if (!uploadFolder.exists()) {
                uploadFolder.mkdirs();
            }

            // 保存ZIP文件到本地
            Files.write(Paths.get(zipFilePath), file.getBytes());

            // 解压ZIP文件
            unzip(zipFilePath, uploadDir);

            return "ZIP file uploaded and extracted successfully.";
        } catch (IOException e) {
            e.printStackTrace();
            return "Error occurred while uploading and extracting the ZIP file.";
        }
    }

    private void unzip(String zipFilePath, String destDir) throws IOException {
        byte[] buffer = new byte[1024];
        try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath))) {
            ZipEntry entry;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                File entryFile = new File(destDir, entry.getName());
                if (entry.isDirectory()) {
                    entryFile.mkdirs();
                } else {
                    File parent = entryFile.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }

                    try (FileOutputStream fos = new FileOutputStream(entryFile)) {
                        int length;
                        while ((length = zipInputStream.read(buffer)) > 0) {
                            fos.write(buffer, 0, length);
                        }
                    }
                }
            }
        }
    }
}
